import { Button, Modal, Popconfirm, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import React, { useEffect, useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { allPanorama, mapCreate, mapList, mapUpdate } from '../service';
import type { MapItem, MapPagination } from './data';
import { commonStatus } from '@/constant/constant';
import { ProFormText, ProFormSelect, ModalForm } from '@ant-design/pro-form';
import PanoramaList from '../components/panorama';
import type { PanoramaItem } from '../panorama/data';


/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: MapItem) => {
  const hide = message.loading('正在添加');

  try {
    await mapCreate({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};


/**
* 更新节点
*
* @param fields
*/
const handleUpdate = async (fields: any, currentRow?: MapItem) => {
  const hide = message.loading('正在修改');

  try {
    await mapUpdate({
      guid: currentRow?.guid,
      ...fields,
    });
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败');
    return false;
  }
};

const Map: React.FC = () => {
  const actionRef = useRef<ActionType>();
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [panoramaData, setPanoramaData] = useState<PanoramaItem[]>([]);


  // 场景
  const [panoramaModalVisible, handlePanoramaModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<MapItem>();

  function updateStatus(guid: string, status: number) {
    mapUpdate({
      guid,
      status
    }).then(() => {
      message.success('更改成功')
      actionRef?.current?.reload()
    }
    )
  }

  async function getAllPanoramaData() {
    const data = await allPanorama({ status: 1 })
    setPanoramaData(data)
  }

  useEffect(() => {
    getAllPanoramaData()
  }, [])

  const columns: ProColumns<MapItem>[] = [
    {
      title: '地图编号',
      dataIndex: 'guid',
      ellipsis: true,
      copyable: true,
    },
    {
      title: '地图名称',
      dataIndex: 'name',
    },
    {
      title: '开始场景',
      search: false,
      dataIndex: 'heard_panorama',
      fieldProps: {
        fieldNames: { label: 'name', value: 'guid' },
        options: panoramaData,
        showSearch: true
      },
      valueType: 'select',
    },

    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: commonStatus,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [

        <a
          key="update"
          // @ts-ignore
          disabled={record.status != 2}
          onClick={() => {
            if (record.status != 2) {
              return
            }
            setCurrentRow(record);
            handleUpdateModalVisible(true);
          }}
        >
          {' '}
          编辑{' '}
        </a>,
        record.status != 1 ? <Popconfirm
          key="confirm"
          title="是否确认启动该项目?"
          onConfirm={() => {
            updateStatus(record.guid, 1)
          }}
          okText="是"
          cancelText="否"
        >
          <a type="link">启动</a>
        </Popconfirm> :
          <Popconfirm
            key="confirm"
            title="是否确认关闭该项目?"
            onConfirm={() => {
              updateStatus(record.guid, 2)
            }}
            okText="是"
            cancelText="否"
          >
            <a type="link">关闭</a>
          </Popconfirm>,
        record.heard_panorama ?
          <a
            key="preview"
            href={`/mall/panorama?guid=${record.heard_panorama}`}
            target='_blank'
            onClick={() => {
              if (!record.heard_panorama) {
                return
              }
            }} rel="noreferrer"
          >
            {' '}
            预览地图{' '}
          </a> : '',
        <a
          key="Panorama"
          onClick={() => {
            setCurrentRow(record);
            handlePanoramaModalVisible(true);
          }}
        >
          {' '}
          场景管理{' '}
        </a>,
      ],
    },
  ];
  // 修改或添加表单 name role avatar 
  const EditBox = (type: boolean = false) => (<>
    <ProFormText
      rules={[
        {
          required: true,
        },
      ]}
      width="md"
      name="name"
      label="地图名称"
    />
    {type ? <ProFormSelect
      name="heard_panorama"
      label="地图开始场景"
      showSearch
      width="md"
      debounceTime={300}
      request={async ({ keyWords }) => {
        try {
          const data = await allPanorama({ name: keyWords, map_id: currentRow?.guid, status: 1 })
          return data.map((item: { guid: string, name: string }) => {
            return {
              value: item.guid,
              label: item.name
            }
          })

        } catch (error) {
          return []
        }

      }}
      placeholder="请选择地图开始场景,输入可搜索"
      rules={[{ required: true, message: '请选择地图开始场景' }]}
    /> : ''}
  </>)

  return (
    <PageContainer>
      <ProTable<MapItem, MapPagination>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="guid"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="detail"
            type="primary"
            onClick={() => {
              // @ts-ignore
              setCurrentRow({})
              handleModalVisible(true)
            }}
          >
            {' '}
            <PlusOutlined /> 创建{' '}
          </Button>,
        ]}
        request={async (params, sort, filter) => {
          return mapList(params);
        }}
        columns={columns}
      />
      {/* 新建modal */}
      <ModalForm
        title="新建"
        width="600px"
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        modalProps={{
          destroyOnClose: true
        }}
        onFinish={async (value) => {

          const success = await handleAdd({ ...value } as MapItem);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >

        {/* 与编辑组件重复抽离 */}
        {EditBox()}

      </ModalForm>
      {/* 编辑 */}
      <ModalForm
        title="编辑"
        width="600px"
        visible={updateModalVisible}
        onVisibleChange={handleUpdateModalVisible}
        modalProps={{
          destroyOnClose: true
        }}
        initialValues={{
          ...currentRow,
        }}

        onFinish={async (value) => {
          const success = await handleUpdate(value, currentRow);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        {EditBox(true)}

      </ModalForm>
      <Modal open={panoramaModalVisible} footer={null} width={1000} onCancel={() => handlePanoramaModalVisible(false)} destroyOnClose>
        <PanoramaList map={currentRow?.guid} />
      </Modal>

    </PageContainer>
  );
};

export default Map;
